package Day2025_03_10;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode1162 {
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    public int maxDistance(int[][] grid) {
        int n = grid.length;
        boolean[][] vis = new boolean[n][n];
        int step = 0;
        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    q.add(new int[]{i, j});
                    vis[i][j] = true;
                }
            }
        }
        while (!q.isEmpty()) {
            int sz = q.size();
            step++;
            while (sz-- != 0) {
                int[] tmp = q.poll();
                int a = tmp[0], b = tmp[1];
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && x < n && y >= 0 && y < n && !vis[x][y]) {
                        q.add(new int[]{x, y});
                        vis[x][y] = true;
                    }
                }
            }
        }
        return step == 1 ? -1 : step - 1;
    }
}
